package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.MyColorBean;
import flc.ast.databinding.ActivityGifMakeBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRelativeLayout;

public class GifMakeActivity extends BaseAc<ActivityGifMakeBinding> {

    public static String sVideoPath;
    private ColorAdapter colorAdapter;
    private int videoWidth, videoHeight;
    private int oldPosition;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            if (mDataBinding.videoView.isPlaying()) {
                mDataBinding.tvDuration.setText(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), getString(R.string.duration_style)) + "/" + TimeUtils.millis2String(MediaUtil.getDuration(sVideoPath), getString(R.string.duration_style)));
                mDataBinding.sbProgress.setProgress(mDataBinding.videoView.getCurrentPosition());
            }
            mHandler.postDelayed(mTaskUpdateTime, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_gif_make;
    }

    @Override
    protected void initView() {
        mDataBinding.ivGifMakeBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvGifMakeConfirm.setOnClickListener(this);

        mDataBinding.rvColorList.setLayoutManager(new GridLayoutManager(mContext, 9));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);

        mHandler = new Handler();
        mDataBinding.sbProgress.setMax((int) MediaUtil.getDuration(sVideoPath));
        mDataBinding.tvDuration.setText("00:00" + "/" + TimeUtils.millis2String(MediaUtil.getDuration(sVideoPath), getString(R.string.duration_style)));
        mDataBinding.videoView.setVideoPath(sVideoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvDuration.setText(TimeUtils.millis2String(MediaUtil.getDuration(sVideoPath), getString(R.string.duration_style)) + "/" + TimeUtils.millis2String(MediaUtil.getDuration(sVideoPath), getString(R.string.duration_style)));
                mDataBinding.ivPlay.setSelected(false);
                mp.seekTo(1);
                stopTime();
            }
        });
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mDataBinding.sbProgress.setMax(mp.getDuration());
                mDataBinding.sbProgress.setProgress(mp.getCurrentPosition());
                videoWidth = mp.getVideoWidth();
                videoHeight = mp.getVideoHeight();
            }
        });
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                StkRelativeLayout.LayoutParams stickerLayoutParams = (StkRelativeLayout.LayoutParams) mDataBinding.txtStickerView.getLayoutParams();
                stickerLayoutParams.width = right - left;
                stickerLayoutParams.height = bottom - top;
                mDataBinding.txtStickerView.setLayoutParams(stickerLayoutParams);
            }
        });
        mDataBinding.etTextContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString();
                mDataBinding.txtStickerView.setText(str);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlay://播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlay.setSelected(false);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlay.setSelected(true);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvGifMakeConfirm://保存
                saveGIF();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        colorAdapter.getItem(oldPosition).setSelect(false);
        colorAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        colorAdapter.getItem(position).setSelect(true);
        colorAdapter.notifyItemChanged(position);
        mDataBinding.txtStickerView.setTextColor(Color.parseColor(colorAdapter.getItem(position).getColor()));
    }

    @Override
    protected void initData() {
        //文字
        List<MyColorBean> listColor = new ArrayList<>();
        listColor.add(new MyColorBean("#000000", true));
        listColor.add(new MyColorBean("#FFFFFF", false));
        listColor.add(new MyColorBean("#E12D2D", false));
        listColor.add(new MyColorBean("#FFA8A8", false));
        listColor.add(new MyColorBean("#FFB652", false));
        listColor.add(new MyColorBean("#FFF62C", false));
        listColor.add(new MyColorBean("#79BA56", false));
        listColor.add(new MyColorBean("#35B9B0", false));
        listColor.add(new MyColorBean("#3F68BC", false));
        listColor.add(new MyColorBean("#9F45F1", false));
        listColor.add(new MyColorBean("#E85C90", false));
        listColor.add(new MyColorBean("#C0C0C0", false));
        listColor.add(new MyColorBean("#CA58C9", false));
        listColor.add(new MyColorBean("#8A72E1", false));
        listColor.add(new MyColorBean("#46D5AF", false));
        listColor.add(new MyColorBean("#5E8C4F", false));
        listColor.add(new MyColorBean("#BEE29E", false));
        colorAdapter.setList(listColor);
        mDataBinding.txtStickerView.setTextColor(Color.parseColor("#000000"));
    }

    public void saveGIF() {
        showDialog(getString(R.string.saving));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String imagePath;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                mDataBinding.txtStickerView.setShowHelpBox(false);
                Bitmap bitmap1 = ImageUtils.view2Bitmap(mDataBinding.txtStickerView);  // 第一个 Bitmap
                Bitmap result = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(), bitmap1.getConfig());
                Canvas canvas = new Canvas(result);
                canvas.drawBitmap(bitmap1, 0f, 0f, null);

                imagePath = FileUtil.generateFilePath(Content.myTemp, ".png");
                boolean save = ImageUtils.save(result, imagePath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean isSave) {
                if (isSave) {
                    EpDraw epDraw = new EpDraw(imagePath, 0, 0, videoWidth, videoHeight, false);
                    epDraw.setRotate(0);
                    String resultFile = FileUtil.generateFilePath(Content.myTemp, ".mp4");//保存到我的视频
                    EpVideo epVideo = new EpVideo(sVideoPath);
                    epVideo.addDraw(epDraw);
                    EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                    EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sVideoPath = resultFile;
                                    saveGIF2();
                                }
                            });
                        }

                        @Override
                        public void onFailure() {
                            dismissDialog();
                            ToastUtils.showShort(R.string.save_failure);
                        }

                        @Override
                        public void onProgress(float progress) {

                        }
                    });
                }
            }
        });


    }

    private void saveGIF2() {
        int scaleWidth = videoWidth;
        int scaleHeight = videoHeight;
        if (scaleWidth * scaleHeight > 960 * 540) {
            //原视频分辨率过大，则要缩小一倍
            scaleWidth = scaleWidth / 2;
            scaleHeight = scaleHeight / 2;
        }
        EditorHolder.editor().video2Gif(sVideoPath, scaleWidth, scaleHeight, 10, 1, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateImgToPublic(mContext, outFilePath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String str) {
                        ToastUtils.showShort(R.string.save_success);
                        startActivity(HomeActivity.class);
                        dismissDialog();
                    }
                });
            }

            @Override
            public void onFailure(String errMsg) {
                ToastUtils.showShort(R.string.ve_covert_gif_fail_tip);
            }

            @Override
            public void onProgress(int progress) {

            }
        });
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTime();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mDataBinding.videoView.seekTo(1);
    }

}